using System;
using System.Collections.Generic;
using BuildWheel;
using UnityEngine;

[Serializable]
public class TFile
{
    public List<File> ls;
}

[CreateAssetMenu(fileName = "FileObject", menuName = "Data/FileObject")]
public class FileObject : ScriptableObject
{
    public Dictionary<string, List<File>> fileDicT = new Dictionary<string, List<File>>();
    [SerializeField] List<string> fileTypeKey = new List<string>();
    [SerializeField] List<TFile> fileTypeValue = new List<TFile>();
    public Folders root;

    #region 生成文件结构

    public void RuntimeRef(List<ResData> ls)
    {
        fileDicT.Clear();
        root = new Folders()
        {
            layer = -1,
            n = "AAResourcesExtends"
        };
        for (int i = 0; i < ls.Count; i++)
        {
            var item = ls[i];
            if (!item.k.StartsWith("Assets_Opt") && !item.k.StartsWith("English/Resource"))
            {
                var arr = item.k.Split("/");
                if (arr.Length > 0)
                {
                    Add(root, arr, item);
                }

                item.n = arr[arr.Length - 1];
            }
        }
    }

    public void EditorRef(List<ResData> ls)
    {
        RuntimeRef(ls);
        fileTypeKey = new List<string>(fileDicT.Keys);
        fileTypeValue.Clear();
        //ScriptableObject 不支持数组多层次
        for (int i = 0; i < fileTypeKey.Count; i++)
        {
            var tfile = new TFile();
            tfile.ls = fileDicT[fileTypeKey[i]];
            fileTypeValue.Add(tfile);
        }
    }

    void Add(Folders folders, string[] arr, ResData ResData)
    {
        if (arr.Length > 1)
        {
            folders.AddChild(arr[0], 0);
            for (int i = 1; i < arr.Length; i++)
            {
                var pLayer = i - 1;
                var parentName = arr[pLayer];
                if (folders.TryFind(pLayer, parentName, out var parentFolders))
                {
                    if (i == arr.Length - 1)
                    {
                        var _n = arr[arr.Length - 1];
                        var file = parentFolders.AddFile(_n, ResData);
                        fileDicT.TryAdd(file.t, new List<File>());
                        fileDicT[file.t].Add(file);
                    }
                    else
                    {
                        parentFolders.AddChild(arr[i], i);
                    }
                }
            }
        }
        else
        {
            folders.AddFile(arr[0], ResData);
        }
    }

    #endregion

    public void GenFileDicT()
    {
        if (fileDicT.Count == 0)
        {
            if (fileTypeKey.Count > 0 && fileTypeValue.Count > 0 && fileTypeKey.Count == fileTypeValue.Count)
            {
                for (int i = 0; i < fileTypeKey.Count; i++)
                {
                    fileDicT[fileTypeKey[i]] = fileTypeValue[i].ls;
                }
            }
        }
    }
}